package com.uy.system.service.impl;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.uy.system.common.constant.SystemConstants;
import com.uy.system.distribute.DistributedCacheService;
import com.uy.system.service.ISysMenuService;
import com.uy.system.service.ISysRoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author LY
 * @create 2024/4/25 16:48
 * @Description 自定义权限加载接口实现类
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private ISysMenuService iSysMenuService;
    @Resource
    private ISysRoleService iSysRoleService;
    @Resource
    private DistributedCacheService distributedCacheService;

    /**
     * 所拥有的权限
     * @param loginId  账号id
     * @param loginType 账号类型
     * @return
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        String key = SystemConstants.SYS_USER_MENU_PERMI_KEY + loginId;
        String value = distributedCacheService.get(key);
        if (StrUtil.isNotBlank(value)){
            JSONArray jsonArray = JSONUtil.parseArray(value);
            return jsonArray.toList(String.class);
        }
        return iSysMenuService.getPermissionList(Long.valueOf(StrUtil.toString(loginId)));
    }

    /**
     * 所拥有的角色
     * @param loginId  账号id
     * @param loginType 账号类型
     * @return
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        String key = SystemConstants.SYS_USER_ROLE_KEY + loginId;
        String value = distributedCacheService.get(key);
        if (StrUtil.isNotBlank(value)){
            JSONArray jsonArray = JSONUtil.parseArray(value);
            return jsonArray.toList(String.class);
        }
        return iSysRoleService.getRoleList(Long.valueOf(StrUtil.toString(loginId)));
    }
}
